from django.contrib import admin

from goods import models
from celery_tasks.html.tasks import generate_static_list_search_html


# Register your models here.

class GoodsCategoryAdmin(admin.ModelAdmin):
    '''
    模型类的站点管理类
    监听“保存”和“删除事件”，异步生成静态化的list.html
    '''

    def save_model(self, request, obj, form, change):
        """
        Given a model instance save it to the database.
        将模型类保存到数据库
        :param request: 本次保存模型类的请求
        :param obj: 本次要保存的模型类
        :param form: 本次保存模型类的表单
        :param change: 本次保存模型类的表单中的不同数据
        :return: None
        """
        # 执行模型保存
        obj.save()

        # 执行完模型的保存之后，异步生成静态化的list.html
        generate_static_list_search_html.delay()

    def delete_model(self, request, obj):
        """
        Given a model instance delete it from the database.
        删除模型数据
        :param request: 本次删除模型类的请求
        :param obj: 本次要删除的模型类
        :return: None
        """
        # 执行删除
        obj.delete()

        # 执行完模型的删除之后，异步生成静态化的list.html
        generate_static_list_search_html.delay()

class SKUAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.id)


class SKUImageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.sku.id)

        # 设置SKU默认图片
        sku = obj.sku
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            sku.save()

    def delete_model(self, request, obj):
        obj.delete()
        from celery_tasks.html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.sku.id)


admin.site.register(models.GoodsCategory, GoodsCategoryAdmin)
admin.site.register(models.GoodsChannel)
admin.site.register(models.Goods)
admin.site.register(models.Brand)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SpecificationOption)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUSpecification)
admin.site.register(models.SKUImage, SKUImageAdmin)